<?php

class ShoppingCartController extends GxController {

    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

    public function accessRules() {
        return array(
            array('allow', // allow all users to perform 'index' and 'view' actions
                'actions' => array('View', 'Create', 'Update', 'delete', 'AddDiscount', 'sendmailtogiftuser'),
                'users' => array('*'),
            ),
            array('allow', // allow authenticated user to perform 'create' and 'update' actions
                'actions' => array('skillPayment', 'skillshopping', 'ResponseEBS', 'Orderdetails'),
                'users' => array('@'),
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    public function actionView() {
        $this->layout = 'false';
        $AllDataCart = Yii::app()->shoppingCart->getPositions();
        $this->render('_view', array('AllDataCart' => $AllDataCart));
        Yii::app()->end();
    }

    /* Add to cart */

    public function actionCreate() {
        $this->layout = 'false';
        if ($_POST['class_course_type'] == "course") {
            $ClassBatch = CourseBatche::model()->findByPk($_POST['ShoppingCart']['batch_id']);
        } else {
            $ClassBatch = ClassBatch::model()->findByPk($_POST['ShoppingCart']['batch_id']);
        }
        if (isset($_POST['GifttofriendWorkshop']['gift_to_user_email'])) {
            Yii::app()->shoppingCart->put($ClassBatch, $_POST['ShoppingCart']['booking_seats'], $_POST['ShoppingCart']['booking_date'], $_POST['ShoppingCart']['batchTime'], $_POST['ShoppingCart']['booking_price'], $_POST['GifttofriendWorkshop']['gift_to_user_email']);
        } else {
            Yii::app()->shoppingCart->put($ClassBatch, $_POST['ShoppingCart']['booking_seats'], $_POST['ShoppingCart']['booking_date'], $_POST['ShoppingCart']['batchTime'], $_POST['ShoppingCart']['booking_price'], '');
        }
        echo CJSON::encode(array(
            'status' => SkillConfig::STATUS_ACTIVE,
            'shopngcartitem' => count(Yii::app()->shoppingCart->getPositions())
        ));
        Yii::app()->end();
    }

    /* Add to cart update */

    public function actionUpdate() {
        $this->layout = false;
        $booking_price = '';
        $bookedSeats = '';
        if ($_POST['classcoursetype'] == "classes") {
            $ClassBatch = ClassBatch::model()->findByPk($_POST['batchId']);
        } else {
            $ClassBatch = CourseBatche::model()->findByPk($_POST['batchId']);
        }
        $bookseats = Yii::app()->db->createCommand()
                ->select('sum(batch_seats) AS seats')
                ->from('skill_purchase_class_course as t left join skill_purchase_order as spo on(t.purchaseorder_id=spo.id)')
                ->where('t.venue_id=' . $ClassBatch->class_venue_id . '  AND order_confirmed=' . SkillConfig::STATUS_ACTIVE)
                ->queryRow();
        $bookedSeats = $bookseats['seats'];
        $restseats = $ClassBatch->seats - $bookedSeats;
        
        if ($_POST['qty'] <= $restseats) {
            $booking_price = ClassBatch::getBatchPriceBySeatsInt($_POST['batchId'], $_POST['qty'], 'int');
            Yii::app()->shoppingCart->put($ClassBatch, $_POST['qty'], $_POST['startdate'],$_POST['batchtiming'], $booking_price,'');
            echo SkillConfig::STATUS_ACTIVE;
        } else {
            echo $restseats . "#@#" . $_POST['qty'];
        }
        Yii::app()->end();
    }

    /* Add to cart remove */

    public function actionDelete() {
        $this->layout = false;
        Yii::app()->shoppingCart->remove($_POST['batchId']);
        if (count(Yii::app()->shoppingCart->getPositions()) == 0) {
            Yii::app()->session['totalamtsession'] = '';
            Yii::app()->session['appliedcoupon'] = '';
        }
        echo CJSON::encode(array(
            'status' => SkillConfig::STATUS_ACTIVE,
            'shopngcartitem' => count(Yii::app()->shoppingCart->getPositions())
        ));

        Yii::app()->end();
    }

    /* collect info from response EBS */

    public function actionResponseEBS() {
        $secret_key = Message::SECRETKEY;
        if (isset($_GET['DR'])) {
            $DR = preg_replace("/\s/", "+", $_GET['DR']);
            $rc4 = new Crypt_RC4($secret_key);
            $QueryString = base64_decode($DR);
            $rc4->decrypt($QueryString);
            $QueryString = explode('&', $QueryString);
            $response = array();
            foreach ($QueryString as $param) {
                $param = explode('=', $param);
                $response[$param[0]] = urldecode($param[1]);
            }
            if ($response['ResponseCode'] == '0') {
                $purchaseOrderModel = PurchaseOrder::model()->findByPk(Yii::app()->session['orderid']);
                if (!empty($purchaseOrderModel)) {
                    $purchaseOrderModel->setAttribute('transaction_id', $response['TransactionID']);
                    $purchaseOrderModel->setAttribute('order_confirmed', SkillConfig::STATUS_ACTIVE);
                    $purchaseOrderModel->save();
                    Yii::app()->session['orderid'] = '';
                }
            } else {
                $this->redirect('site/index');
            }
        }
        $this->render('_response', array('orderId' => $purchaseOrderModel->id, 'totalCost' => $purchaseOrderModel->total_price, 'transaction_id' => $purchaseOrderModel->transaction_id, 'order_date_time' => $purchaseOrderModel->order_date_time));
    }

    public function actionskillshopping() {
        $couponid = '';
        $vanueAddress = '';
        $earlyDscount = '';
        $groupDscount = '';
        $cost = '';
        $couponcode = '';
        $loginuserId = getLoginUserId();
        $loginuserDetail = Users::getFrontEndUser($loginuserId);
        $username = !empty($loginuserDetail->first_name) ? $loginuserDetail->first_name : $loginuserDetail->user->username;
        $useremail = Yii::app()->user->name;
        if (Yii::app()->user->hasState('appliedcoupon') <> "") {
            $couponcode = Yii::app()->user->hasState('appliedcoupon');
            $coupon = Coupons::getCouponType($couponcode);
            $couponid = !empty($coupon) ? $coupon->id : '';
        }
        $purchaseOrderModel = new PurchaseOrder;
        $purchaseOrderModel->setAttribute('transaction_id', time());
        $purchaseOrderModel->setAttribute('total_price', Yii::app()->session['totalamountcart']);
        $purchaseOrderModel->setAttribute('order_date_time', date("Y-m-d H:i:s"));
        $purchaseOrderModel->setAttribute('users_id', getLoginUserId());
        $purchaseOrderModel->setAttribute('order_confirmed', SkillConfig::STATUS_DEACTIVE);
        $purchaseOrderModel->setAttribute('coupons_code', $couponid);
        if ($purchaseOrderModel->save()) {
            Yii::app()->session['orderid'] = $purchaseOrderModel->id;
            $AllDataCart = Yii::app()->shoppingCart->getPositions();
            foreach ($AllDataCart as $AllDataCart) {
                $PurchaseClassCourseModel = new PurchaseClassCourse;
                $PurchaseClassCourseModel->setAttribute('purchaseorder_id', $purchaseOrderModel->id);
                $PurchaseClassCourseModel->setAttribute('batch_start_date', $AllDataCart->startdate);
                $PurchaseClassCourseModel->setAttribute('batch_start_time', $AllDataCart->batchtiming);
                $PurchaseClassCourseModel->setAttribute('batch_seats', $AllDataCart->quantity);
                if ($AllDataCart->classes_id <> "") {
                    $batchPrice = ClassBatch::getBatchPricebyBatchId($AllDataCart->id);
                    $vanueAddress = ClassVenue::getVenueAddressVyClassCoursebatchId('class', $AllDataCart->id);
                    $venueId = ClassVenue::getVenueId('class', $AllDataCart->id);
                    $PurchaseClassCourseModel->setAttribute('classes_id', $AllDataCart->classes_id);
                    $PurchaseClassCourseModel->setAttribute('class_batch_id', $AllDataCart->id);
                } else {
                    $vanueAddress = ClassVenue::getVenueAddressVyClassCoursebatchId('course', $AllDataCart->id);
                    $venueId = ClassVenue::getVenueId('course', $AllDataCart->id);
                    $PurchaseClassCourseModel->setAttribute('courses_id', $AllDataCart->classes_id);
                    $PurchaseClassCourseModel->setAttribute('course_batch_id', $AllDataCart->id);
                }
                $PurchaseClassCourseModel->setAttribute('batch_price', $batchPrice);
                $earlyDscount = ClassBatch::getearlyDscountByBatch($AllDataCart->id, $AllDataCart->quantity);
                $groupDscount = ClassBatch::getgroupDscountByBatch($AllDataCart->id, $AllDataCart->quantity);
                $PurchaseClassCourseModel->setAttribute('batch_early_dicount', $earlyDscount);
                $PurchaseClassCourseModel->setAttribute('batch_group_discount', $groupDscount);
                $PurchaseClassCourseModel->setAttribute('venue_deatils', $vanueAddress);
                $PurchaseClassCourseModel->setAttribute('venue_id', $venueId);
                $PurchaseClassCourseModel->save();
                if (!empty($AllDataCart->giftuseremail)) {
                    GifttofriendWorkshop::saveGifttofriendWorkshopdetails($purchaseOrderModel, $AllDataCart->giftuseremail);
                }
            }
        }
        $this->render('_form_EBSPOP', array('orderId' => $purchaseOrderModel->id, 'totalCost' => $purchaseOrderModel->total_price, 'loginuserId' => $loginuserId, 'useremail' => $useremail, 'username' => $username));
    }

    /* Add to cart remove */

    public function actionOrderdetails() {
        if (!empty(Yii::app()->session['orderid'])) {
            $purchaseOrderModel = PurchaseOrder::model()->findByPk(Yii::app()->session['orderid']);
            $purchaseOrderModel->setAttribute('transaction_id', time());
            $purchaseOrderModel->setAttribute('order_confirmed', SkillConfig::STATUS_ACTIVE);
            $purchaseOrderModel->save();
            Yii::app()->session['orderid'] = '';
        }

        $this->render('_response', array('orderId' => $purchaseOrderModel->id, 'totalCost' => $purchaseOrderModel->total_price, 'transaction_id' => $purchaseOrderModel->transaction_id, 'order_date_time' => $purchaseOrderModel->order_date_time));
    }

    public function actionAddDiscount() {
        $date = date('Y-m-d');
        $valid_err = '';
        $couponModel = Coupons::model()->findByAttributes(array('name' => trim($_POST['discount_code']), 'status' => SkillConfig::STATUS_ACTIVE));
        if (!empty($couponModel)) {
            $couponError = Coupons::getCouponRescrtion(Yii::app()->user->setState('appliedcoupon', trim($_POST['discount_code'])));
            if ($couponError != 'false') {
                Yii::app()->user->setState('appliedcoupon', trim($_POST['discount_code']));
                echo SkillConfig::STATUS_ACTIVE;
            } else {
                Yii::app()->user->setState('appliedcoupon', 'NUll');
            }
        } else {
            echo 'Invalid Coupon';
        }
    }

    public function actionsendmailtogiftuser($purchaseId, $emailId, $transaction_id, $order_date_time) {
        $purchase = PurchaseClassCourse::model()->find('purchaseorder_id=' . $purchaseId);
        if (!empty($purchase)) {
            $username = Users::model()->findByPk(getLoginUserId());
            $userdetails = $username->username;
            $userdetails = Users::getFrontEndUser(getLoginUserId());
            if (!empty($userdetails)) {
                $userdetails = $userdetails->first_name . '  ' . $userdetails->last_name;
            }
            ob_start();
            echo $this->renderPartial('_giftClassmailTemplate', array('purchase' => $purchase, 'transaction_id' => $transaction_id, 'order_date_time' => $order_date_time));
            $mailmodel = EmailTemplate::model()->findByPk(Message::GIFT_A_CLASS);
            $content = ob_get_clean();
            $mailbody = array('value' => $mailmodel->body, 'type' => 'html');
            $subject = $mailmodel->subject . ' ' . $userdetails . '!';
            $userName = $emailId;
            $arrayFind = array('[username]', '[from_user_name]', '[order_details]');
            $arrayReplace = array($userName, $userdetails, $content);
            $mailbody = str_replace($arrayFind, $arrayReplace, $mailbody);
            $mailtemp = Template::model()->findByPk($mailmodel->template_id);
            $body = $this->renderPartial('/mails/' . $mailtemp->filename, array('mailbody' => $mailbody['value']), true, false);

            try {
                SkillSendMail::SendMail($emailId, $subject, $body);
            } catch (Exception $e) {
                echo $e;
                exit;
            }
        }
    }

}